package com.cjh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjh.common.BaseContext;
import com.cjh.common.R;
import com.cjh.entity.User;
import com.cjh.service.UserService;
import com.cjh.utils.SMSUtils;
import com.cjh.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /*发送短信*/
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone=user.getPhone();
        //生成随机的4位验证码
        if (!StringUtils.isEmpty(phone)){
            String code= ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("验证码是{}",code);
            //调用阿里云提供的短信服务
            // SMSUtils.sendMessage();
            session.setAttribute(phone,code);
            session.setAttribute("cjh",code);


            return R.success(code);
        }

       return R.error("短信发送失败");
    }



    /*发送短信*/
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){

        //获取手机号
        String phone =map.get("phone").toString();
        //获取验证码
        String code =  map.get("code").toString();
        //从session中获取保存的验证码
        Object sessionCode = session.getAttribute(phone);
        //进行验证码的比对
        if(sessionCode!=null&& sessionCode.equals(code)){
            LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }

            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }


    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出账号");
    }
}
